// ignore_for_file: constant_identifier_names
import 'dart:convert';
import 'package:get/get.dart';

import '../../pages/index.dart';
import '../index.dart';

///
///Author: YYF
///Date: 2022-02-06 16:45:11
///Description:
///

/// 用户 - 配置信息

/// 设备是否第一次打开
const String STORAGE_DEVICE_FIRST_OPEN_KEY = 'device_first_open';

/// 用户是否同意第三方推送政策
const String STORAGE_AGREE_THIRD_SDK_KEY = 'agree_third_sdk';

/// 多语言
const String STORAGE_LANGUAGE_CODE = 'language_code';

///token
const String STORAGE_USER_TOKEN_KEY = 'user_token';

///用户信息
const String USER_INFO = 'user_info';

class UserStore extends GetxController {
  static UserStore get to => Get.find();

  // 令牌 token
  var token = ''.obs;

  bool get hasToken => token.isNotEmpty;
  UserInfo get userinfo => getUserInfo();

  @override
  void onInit() {
    super.onInit();
    token.value = StorageService.to.getString(STORAGE_USER_TOKEN_KEY);
  }

  // 保存 token
  Future<void> setToken(String value) async {
    await StorageService.to.setString(STORAGE_USER_TOKEN_KEY, value);
    token.value = value;
    return;
  }

  // 清除 token
  Future<void> cleanToken() async {
    await StorageService.to.remove(STORAGE_USER_TOKEN_KEY);
    await StorageService.to.remove(USER_INFO);
    // await StorageService.to.remove(USER_ROLE_ID);
    token.value = '';
  }

  // 保存 userInfo
  Future<void> setUserInfo(Map<String, dynamic> userInfo) async {
    await StorageService.to.setString(USER_INFO, jsonEncode(userInfo));
  }

  // 获取 userInfo
  UserInfo getUserInfo() {
    String user = StorageService.to.getString(USER_INFO);
    if (user.isEmpty) {
      return UserInfo();
    }
    return UserInfo.fromJson(jsonDecode(user));
  }

  onLogout() async {
    cleanToken();
    UserStore.to.cleanToken();
    UserStore.to.token.value = '';
    UserStore.to.update();
    StorageService.to.remove('StationAnimation');
    // await controller.setBusinessman(false);
    // Get.offAllNamed(AppRoutes.LOGIN);
    // const RouteSettings(name: AppRoutes.LOGIN);
    Get.back();
    Get.toNamed(AppRoutes.LOGIN);
    ApplicationController _app = Get.find()..state.tabbarCurrentIndex = 0;
  }
}
